'use client';
import PageTitle from '@/components/admin/common/PageTitle';
import Loading from '@/components/common/Loading';
import message from '@/components/common/message';
import { SESSION_ROLES, SESSION_PERMISSIONS } from '@/config/settings';
import request from '@/utils/request';
import React, { useCallback, useEffect, useState } from 'react'
import Checkbox from '@/components/admin/common/Checkbox';
import Popup from '@/components/admin/common/Popup';
import PopupHeader from '@/components/admin/common/PopupHeader';
import isEqual from 'lodash/isEqual';
import SuperInput from '@/components/admin/common/SuperInput';
import SuperMultiCheckbox from '@/components/admin/common/SuperMultiCheckbox';
import {Settings} from 'lucide-react'
import IconButton from '@/components/common/IconButton';

export default function Roles() {
  const [loaded, setLoaded] = useState(false);
  const [roles, setRoles] = useState([]);
  const [forbidEditId, setForbidEditId] = useState([1]);
  const [forbidDeleteId, setForbidDeleteId] = useState([1, 2]);
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const [originEditingRole, setOriginEditingRole] = useState({});
  const [editingRole, setEditingRole] = useState({});
  const [isEding, setIsEding] = useState(false);
  const [permissions, setPermissions] = useState([]);
  const [deleteRolesList, setDeleteRolesList] = useState([]);
  const [isAdding, setIsAdding] = useState(false);

  const fetchRoles = useCallback(() => {
    request('/api/admin/roles', { method: 'GET' })
      .then(res => {
        if (res.code === 0) {
          setRoles(res.data);
          sessionStorage.setItem(SESSION_ROLES, JSON.stringify(res.data));
          setLoaded(true);
        } else {
          message.error(res.codeMap[res.code]);
        }
      })
  }, []);

  useEffect(() => {
    if (sessionStorage.getItem(SESSION_ROLES)) {
      setRoles(JSON.parse(sessionStorage.getItem(SESSION_ROLES)));
      setLoaded(true);
    } else {
      fetchRoles();
    }
  }, [fetchRoles]);

  const fetchPermissions = useCallback(() => {
    request('/api/admin/permissions', { method: 'GET' })
      .then(res => {
        if (res.code === 0) {
          setPermissions(res.data);
          sessionStorage.setItem(SESSION_PERMISSIONS, JSON.stringify(res.data));
        } else {
          message.error(res.codeMap[res.code]);
        }
      })
  }, []);

  useEffect(() => {
    if (sessionStorage.getItem(SESSION_PERMISSIONS)) {
      setPermissions(JSON.parse(sessionStorage.getItem(SESSION_PERMISSIONS)));
    } else {
      fetchPermissions();
    }
  }, [fetchPermissions]);

  const openPopup = (item) => {
    setIsAdding(false);
    setOriginEditingRole(item);
    setEditingRole(item);
    setIsPopupOpen(true);
  };

  useEffect(() => {
    const res = !isEqual(originEditingRole, editingRole);
    setIsEding(res);
  }, [originEditingRole, editingRole])

  const closePopup = () => {
    setIsAdding(false);
    setOriginEditingRole({});
    setEditingRole({});
    setIsPopupOpen(false);
  };

  const changeRoleHandle = () => {
    if (!isEding) {
      closePopup();
      return;
    }
    if (isAdding) {
      request('/api/admin/roles', { method: 'POST', body: JSON.stringify(editingRole) })
        .then(res => {
          if (res.code === 0) {
            message.success('添加成功');
            fetchRoles();
            closePopup();
          } else {
            message.error(res.codeMap[res.code]);
          }
        });
    } else {
      request('/api/admin/roles', { method: 'PUT', body: JSON.stringify(editingRole) })
        .then(res => {
          if (res.code === 0) {
            message.success('修改成功');
            fetchRoles();
            closePopup();
          } else {
            message.error(res.codeMap[res.code]);
          }
        });
    }
  };

  const resetRoleInfo = () => {
    setEditingRole(originEditingRole);
  };

  const checkedEvent = (id, value) => {
    if (value) {
      setDeleteRolesList(prev => [...prev, id]);
    } else {
      setDeleteRolesList(prev => prev.filter(item => item !== id));
    }
  }

  const handleChange = (key, value) => {
    setEditingRole({ ...editingRole, [key]: value });
  }

  const initAddRole = () => {
    const maxRoleCode = Math.max(...roles.map(item => item.code)) + 1;
    const initValuse = { name: '', description: '', code: maxRoleCode, permissions: [] };
    setOriginEditingRole(initValuse);
    setEditingRole(initValuse);
  }

  const addRoleOpenPopupEvent = () => {
    setIsAdding(true);
    initAddRole();
    setIsPopupOpen(true);
  }

  const deleteEvent = () => {
    if (deleteRolesList.length > 0) {
      request('/api/admin/roles', { method: 'DELETE', body: JSON.stringify(deleteRolesList) })
        .then(res => {
          if (res.code === 0) {
            message.success('删除成功');
            fetchRoles();
            setDeleteRolesList([]);
          } else {
            message.error(res.codeMap[res.code]);
          }
        });
    }
  }

  const content = (
    <div>
      <Popup isOpen={isPopupOpen} onClose={closePopup}>
        <PopupHeader title={'编辑角色'} buttonText={isEding ? '保存' : '关闭'} onButtonClick={changeRoleHandle} extraButtonText={isEding ? '重置' : ''} onExtraButtonClick={resetRoleInfo} />
        <form onSubmit={e => e.preventDefault()}>
          <SuperInput label={'名称'} autoComplete={'name'} state={forbidEditId?.includes(editingRole.id) ? false : true} value={editingRole?.name} handleChange={(value) => handleChange('name', value)} />
          <SuperInput label={'描述'} autoComplete={'description'} state={forbidEditId?.includes(editingRole.id) ? false : true} value={editingRole?.description} handleChange={(value) => handleChange('description', value)} />
          <SuperInput label={'权限代码'} autoComplete={'code'} state={forbidDeleteId?.includes(editingRole.id) ? false : true} value={String(editingRole?.code)} handleChange={(value) => handleChange('code', Number(value))} />
          <SuperMultiCheckbox label={'权限'} state={forbidEditId?.includes(editingRole.id) ? false : true} options={permissions} values={editingRole?.permissions} onChange={(value) => handleChange('permissions', value)} />
        </form>
      </Popup>
      <PageTitle title="角色管理" buttonText={'添加'} onButtonClick={addRoleOpenPopupEvent} extraButtonText={deleteRolesList.length > 0 ? '删除' : ''} onExtraButtonClick={deleteEvent} />
      <div className='flex py-3 sticky top-[48px] bg-[#FFFFFF] z-10 items-center px-4 text-xs rounded-t-xs border-b border-gray-200 text-[#333333] font-semibold'>
        <div className='flex-2 flex justify-start gap-2'><span className='pl-4'>用户信息</span></div>
        <div className='flex-1 flex justify-start gap-2'>权限代码</div>
        <div className='flex-1 flex justify-end gap-2 pr-2'>编辑</div>
      </div>
      <div className='rounded-b-sm bg-white'>
        {roles.length > 0 && roles.map(item => (
          <div key={item.id} className='flex items-center justify-between px-4 transition-all duration-100 py-2 bg-white cursor-pointer rounded-xs border-b-1 border-gray-200'>
            <div className='left flex-2 flex justify-left align-center'>
              <Checkbox state={forbidDeleteId?.includes(item.id) ? false : true} checked={deleteRolesList.includes(item.id) ? true : false} onChange={(value) => checkedEvent(item.id, value)} />
              <span className='text-xs pl-2 grid items-center'>{item.name}</span>
              {item.description && <span className='text-xs ml-1 flex items-center'>（{item.description}）</span>}
            </div>
            <div className='center flex-1 flex justify-left'>{item.code}</div>
            <div className='right flex-1 flex justify-end'> <IconButton onClick={() => openPopup(item)}><Settings color='#FFFFFF'/></IconButton> </div>
          </div>
        )
        )}
      </div>
    </div>
  )

  return (
    <div>
      {loaded ? content : <Loading />}
    </div>
  )
}
